/// @file MyUi.cpp  @version 1.0 @date 05/01/2012
/// @author BlahGeek@Gmail.com

#include "MyUi.h"

bool MyWin::getUrl(){
	QByteArray html = page->readAll();
	int index_ = html.indexOf("soundFile:\"");
	if(index_ !=-1){
		index_ += strlen("soundFile:\"");
		QByteArray encoded;
		for(;html[index_] != '"';index_++)
			encoded += html[index_];
		downloadUrl = QString(base64_decode(encoded.data()).c_str());
		return true;
	}
	return false;
}

MyWin::MyWin(){
	setupUi(this);
	downloader = new QNetworkAccessManager;
	downloader->setCookieJar(new QNetworkCookieJar);
	connect(lineEdit, SIGNAL(returnPressed()), 
			this, SLOT(downloadPage()));
	page = data = NULL;
}

void MyWin::print_msg(const QString & msg){
	setWindowTitle(msg);
}

void MyWin::downloadPage(){
	if(page!=NULL)
		delete page;
	if(data!=NULL)
		delete data;
	lineEdit->setEnabled(false);
	page = data = NULL;
	refUrl = QString("http://") + label_2->text() + lineEdit->text();
	page = downloader->get(QNetworkRequest(QUrl(refUrl)));
	connect(page, SIGNAL(finished()), 
			this, SLOT(downloadData()));
}

void MyWin::downloadError(){//QNetworkReply::NetworkError code_){
	lineEdit->setEnabled(true);
	fout.close();
	print_msg(QString("Error occured."));
//			if(page!=NULL)
////				page->deleteLater();
//				delete page;
//			if(data!=NULL)
////				data->deleteLater();
//				delete data;
}

void MyWin::downloadData(){
	if( page->error() != QNetworkReply::NoError ){
		downloadError();
		return;
	}
	if(!getUrl()){
		downloadError();//QNetworkReply::NoError);
		return;
	}
	print_msg(QString("URL found: ") + downloadUrl );
	fout.open(downloadUrl.split("/").last().toStdString().c_str());
	data = downloader->get(QNetworkRequest(QUrl(downloadUrl)));
	connect(data, SIGNAL(downloadProgress(qint64, qint64)), 
			this, SLOT(setProgress(qint64, qint64)));
	connect(data, SIGNAL(finished()), 
			this, SLOT(allFinished()));
}

void MyWin::allFinished(){
	if( data->error() != QNetworkReply::NoError ){
		downloadError();
		return;
	}
	lineEdit->setEnabled(true);
//	if(page!=NULL)
//		page->deleteLater();
//	if(data!=NULL)
//		data->deleteLater();
	print_msg(QString("Complete."));
}

void MyWin::setProgress(qint64 value, qint64 total){
	QByteArray s = data->readAll();
	fout.write(s.data(), s.size());
	progressBar->setMaximum(total);
	progressBar->setValue(value);
}
